import axios from 'axios'
import store from '../store'
import Cookie from 'js-cookie'
import { Message } from 'element-ui'
import Vue from 'vue'

let baseURL = process.env.BASE_API
if (process.env.NODE_ENV !== 'production') {
    baseURL = localStorage.getItem('baseURL') ? localStorage.getItem('baseURL') : baseURL
}
// 创建axios实例
let service = axios.create({
    // api 的 base_url
    baseURL: baseURL,
    // 请求超时时间
    timeout: 300000
})

if (Cookie.get('token')) {
    // 让每个请求携带 token 请根据实际情况自行修改
    service.defaults.headers['Authorization'] = 'Bearer ' + Cookie.get('token')
}

// request拦截器
service.interceptors.request.use(
    config => {
        let url = window.location.href
        if (!url.includes('/login')) {
            // 开启Loading
            store.dispatch('UpdateLoading', true)
        }
        config.data = Vue.prototype.removeSpaces(config.data)
        if (config.data && config.data.departmenId === '') {
            config.data.departmenId = null
        }
        if (config.data && config.data.departmenID === '') {
            config.data.departmenID = null
        }
        return config
    }
)

// 全局拦截响应
service.interceptors.response.use(
    response => {
        // 关闭Loading
        store.dispatch('UpdateLoading', false)
        return new Promise(resolve => {
            if (response.data.code && response.data.code.toString() === '401') {
                Cookie.set('timeOut', 'timeOut')
                store.dispatch('user/logout').then(() => {
                    // 为了重新实例化vue-router对象 避免bug
                    location.reload()
                })
            } else {
                resolve(response.data)
            }
        })
    },
    error => {
        // 关闭Loading
        store.dispatch('UpdateLoading', false)
        if (error.message.includes('401')) {
            Cookie.set('timeOut', 'timeOut')
            store.dispatch('user/logout').then(() => {
                window.location.href = '/login'
            })
        }
        if (error.message.includes('403')) {
            Message.error('无权限操作')
        }
        return Promise.reject(error)
    }
)
export default service
